package com.ypinkj.app.api;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Function;
import com.ypinkj.app.annotation.UserLoginToken;
import com.ypinkj.app.entity.CCompany;
import com.ypinkj.app.entity.Dict;
import com.ypinkj.app.mapper.CCompanyMapper;
import com.ypinkj.app.service.CCompanyService;
import com.ypinkj.app.service.TokenService;
import com.ypinkj.app.service.redis.RedisService;
import com.ypinkj.app.utils.MD5Util;
import com.ypinkj.app.utils.resultutils.Result;
import com.ypinkj.app.utils.resultutils.ResultPage;
import com.ypinkj.app.utils.resultutils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LF
 * @since 2020-09-29
 */
@Api(tags = "企业")
@RestController
@RequestMapping("/c-company")
public class CCompanyController {

    @Autowired
    CCompanyMapper companyMapper;

    @Autowired
    private CCompanyService cCompanyService;


    @Autowired
    RedisService redisService;
    @Autowired
    TokenService tokenService;


    @UserLoginToken
    @PostMapping
    @ApiOperation(value = "保存")
    public Result save(CCompany cCompany) {

        System.out.println("开始保存" + cCompany);


        if (StringUtils.isNotBlank(cCompany.getPassword()) == true && StringUtils.isNotBlank(cCompany.getPhone()) == true && StringUtils.isNotBlank(cCompany.getCompanylogin()) == true &&
                StringUtils.isNotBlank(cCompany.getCompanyname()) &&
                StringUtils.isNotBlank(cCompany.getEmail()) && StringUtils.isNotBlank(cCompany.getQualificationPic())
        ) {
            LambdaQueryWrapper<CCompany> queryWrapper = new LambdaQueryWrapper<>();


            queryWrapper.eq(CCompany::getPassword, cCompany.getPassword())
                    .eq(CCompany::getPhone, cCompany.getPhone())
                    .eq(CCompany::getCompanylogin, cCompany.getCompanylogin())
                    .eq(CCompany::getStatus, cCompany.getStatus())
                    .eq(CCompany::getCompanyname, cCompany.getCompanyname())
                    .eq(CCompany::getToken, cCompany.getToken())
                    .eq(CCompany::getQualificationPic, cCompany.getQualificationPic())
                    .eq(CCompany::getEmail, cCompany.getEmail());


            Integer integer = companyMapper.selectCount(queryWrapper);
            if (integer > 0) {
                return ResultUtil.error(500, "数据重复");
            }
            companyMapper.insert(cCompany);
            return ResultUtil.success();
        }
        return ResultUtil.errorMsg();
    }

    @UserLoginToken
	@DeleteMapping("/{id}")
	@ApiOperation(value = "根据id获取")
	public Result get(@PathVariable String id) {
        CCompany cCompany = companyMapper.selectById(id);
        return ResultUtil.success(cCompany);
	}

//    @UserLoginToken
//    @PutMapping
//    @ApiOperation(value = "修改")
//    public Result update(Dict dict) {
//        if (StringUtils.isNotBlank(dict.getK()) && StringUtils.isNotBlank(dict.getType()) == true && StringUtils.isNotBlank(dict.getVal()) == true) {
//            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(Dict::getK, dict.getK())
//                    .eq(Dict::getType, dict.getType())
//                    .eq(Dict::getVal, dict.getVal());
//            Integer integer = dictDao.selectCount(queryWrapper);
//            if (integer > 0) {
//                return ResultUtil.error(500, "数据重复");
//            }
//            dictDao.updateDict(dict);
//            return ResultUtil.success();
//        }
//        return ResultUtil.errorMsg();
//    }

    @ApiOperation(value = "注册")
    @PutMapping
    public Result add(CCompany company, String code) {
        if (company != null && company.getPassword() != null) {
            String pattern = "^[a-zA-Z0-9]{6,9}$";
            if (!Pattern.matches(pattern, company.getPassword())) {
                return ResultUtil.error(500, "密码格式错误");
            }
            //如果密码不为空则加密验证
            company.setPassword(MD5Util.string2MD5(company.getPassword()));
        } else {
            return ResultUtil.error(500, "密码不能为空");
        }

        if (company.getPhone() == null) {
            return ResultUtil.error(500, "手机号不能为空");
        }
        //判断手机号是否已注册
        LambdaQueryWrapper<CCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CCompany::getPhone, company.getPhone());
        Integer count = companyMapper.selectCount(queryWrapper);
        if (count > 0) {
            return ResultUtil.error(500, "手机号已存在");
        } else {
            //正则验证手机号
            String pattern = "[1][3,4,5,6,7,8,9][0-9]{9}";
            if (!Pattern.matches(pattern, company.getPhone())) {
                return ResultUtil.error(500, "手机号格式错误");
            }
        }

        //此处开发时注释，上线后打开验证手机
        //获取redis中的手机号的验证码 code是表单提交的验证码
        /*String key = redisService.getValueByKey(company.getPhone());
        //System.out.println(key+"=============="+code);
        if (key==null) {
            return ResultUtil.error(500, "验证码已失效,请重新获取");
        }else {
            if (!key.equals(code)){
                return ResultUtil.error(500, "验证码不正确,请重新获取");
            }
        }*/

        LambdaQueryWrapper<CCompany> queryWrappers = new LambdaQueryWrapper<>();
        queryWrappers.eq(CCompany::getCompanylogin, company.getCompanylogin());
        Integer integer = companyMapper.selectCount(queryWrappers);
        //用户名6-12位字母+数字
        //密码6-9位数字+密码
        //手机号正则
        if (integer > 0) {
            return ResultUtil.error(500, "用户已存在");
        } else {
            //正则验证用户名
            String pattern = "^[a-zA-Z0-9]{6,12}$";
            if (!Pattern.matches(pattern, company.getCompanylogin())) {
                return ResultUtil.error(500, "用户名格式错误");
            }
        }
        //注册时默认 审核中 0 审核通过 1 未通过 2
        company.setStatus("0");
        //注册设置第一次登录值为0 否则为1
        company.setFirstLogin(0);
        //保存用户
        companyMapper.insert(company);

        return ResultUtil.success();
    }

    //登录
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Object login(CCompany company, String code) {
        System.out.println("进入登录");
        //第一种登录方式   用户名+密码
        if (null == company.getPhone()) {
            if (company != null && company.getPassword() != null) {
                //如果密码不为空则加密验证
                company.setPassword(MD5Util.string2MD5(company.getPassword()));
            } else {
                return ResultUtil.error(500, "密码不能为空");
            }

            CCompany name = companyMapper.findByName(company.getCompanylogin());
            if (name == null) {
                return ResultUtil.error(500, "登录失败,用户不存在");
            } else {
                if (!name.getStatus().equals("1")) {
                    return ResultUtil.error(500, "登录失败,用户未通过审核");
                }
                if (!name.getPassword().equals(company.getPassword())) {
                    return ResultUtil.error(500, "登录失败,密码错误");
                } else {
                    String token = tokenService.getTokenCompany(name);
                    //登陆成功更新用户token
                    name.setToken(token);
                    name.setUpdateTime(new Date());//登录时间
                    name.setFirstLogin(name.getFirstLogin() + 1);
                    companyMapper.UpdateUserToken(name);
                    return ResultUtil.success(name);
                }
            }
        } else {
            //第二种登录方式   手机号+验证码
            //判断手机号是否已注册
            CCompany cCompany = companyMapper.findByPhone(company.getPhone());
            if (cCompany == null) {
                return ResultUtil.error(500, "登录失败,手机号不存在");
            } else {
                if (!cCompany.getStatus().equals("1")) {
                    return ResultUtil.error(500, "登录失败,用户未通过审核");
                }
                //获取redis中的手机号的验证码 code是表单提交的验证码
                String key = redisService.getValueByKey(cCompany.getPhone());
                if (key != null) {
                    if (!key.equals(code)) {
                        return ResultUtil.error(500, "登录失败,验证码错误");
                    } else {
                        String token = tokenService.getTokenCompany(cCompany);
                        //登陆成功更新用户token
                        cCompany.setToken(token);
                        cCompany.setUpdateTime(new Date());
                        cCompany.setFirstLogin(cCompany.getFirstLogin() + 1);
                        companyMapper.UpdateUserToken(cCompany);
                        return ResultUtil.success(cCompany);
                    }
                } else {
                    return ResultUtil.error(500, "验证码已失效,请重新获取");
                }
            }

        }
    }

    //验证公司是否已被注册
    @ApiOperation(value = "验证公司是否已被注册")
    @PostMapping("vaildCompanyName")
    public Result vaildCompanyName(String name) {
        CCompany cCompany = companyMapper.findByLoginName(name);
        return cCompany == null ? ResultUtil.success() : ResultUtil.error(500, "该公司已被注册");
    }

    //退出登录
    @ApiOperation(value = "企业用户退出登录", notes = "id:为当前用户id")
    @DeleteMapping
    public Result layout(String id) {
        CCompany company = new CCompany();
        company.setToken("");
        company.setUpdateTime(new Date());
        company.setId(id);
        int i = companyMapper.layout(company);
        return i > 0 ? ResultUtil.success() : ResultUtil.errorMsg();
    }

    /**
     * 热门公司接口
     * <p>
     * 肖守凯
     */

   // @UserLoginToken
    @PostMapping("/popularCompanies")
    public ResultPage popularCompanies(Integer page, Integer limit) {


        /*
         *  配置默认值 的分页
         *
         */
        page = page == null ? 1 : page;
        limit = limit == null ? 2 : limit;


        List<CCompany>  cCompanies=cCompanyService.getPopularCompanies(page,limit);



        QueryWrapper<CCompany> wrapper = new QueryWrapper<>();

        wrapper.orderByDesc("createTime");//排序

        IPage<CCompany> pageCCompany = new Page(page - 1, limit);


        IPage<CCompany> page1 = cCompanyService.page(pageCCompany, wrapper);

        return ResultUtil.successCount(page1, page1.getTotal());
    }

    @UserLoginToken
    @ApiOperation(value = "后台页面分页数据")
    @GetMapping("/getPageCompanyList")
    public Object getPageCompanyList(int page, int limit, CCompany cCompany) {
        //设置分页参数
        PageHelper.startPage(page, limit);
        //查询条件
        LambdaQueryWrapper<CCompany> queryWrapper = new LambdaQueryWrapper<>();

        if (cCompany.getCompanyname() != null && cCompany.getCompanyname() != "") {
            queryWrapper.eq(CCompany::getCompanyname, cCompany.getCompanyname());
        }
        if (cCompany.getPassword() != null && cCompany.getPassword() != "") {
            queryWrapper.eq(CCompany::getPassword, cCompany.getPassword());
        }


        if (cCompany.getPhone() != null && cCompany.getPhone() != "") {
            queryWrapper.eq(CCompany::getPhone, cCompany.getPhone());
        }


        if (cCompany.getCompanylogin() != null && cCompany.getCompanylogin() != "") {

            queryWrapper.eq(CCompany::getCompanylogin, cCompany.getCompanylogin());
        }


        if (cCompany.getFirstLogin() != null && cCompany.getFirstLogin() != 0) {
            queryWrapper.eq(CCompany::getFirstLogin, cCompany.getFirstLogin());
        }
        if (cCompany.getStatus() != null && cCompany.getStatus() != "") {
            queryWrapper.eq(CCompany::getStatus, cCompany.getStatus());
        }
        if (cCompany.getEmail() != null && cCompany.getEmail() != "") {
            queryWrapper.eq(CCompany::getEmail, cCompany.getEmail());
        }
        if (cCompany.getToken() != null && cCompany.getToken() != "") {
            queryWrapper.eq(CCompany::getToken, cCompany.getToken());
        }
        if (cCompany.getQualificationPic() != null && cCompany.getQualificationPic() != "") {
            queryWrapper.eq(CCompany::getQualificationPic, cCompany.getQualificationPic());
        }
        if (cCompany.getDelFlag() != null && cCompany.getDelFlag() != "") {
            queryWrapper.eq(CCompany::getDelFlag, cCompany.getDelFlag());
        }
        if (cCompany.getCreateTime() != null) {
            queryWrapper.eq(CCompany::getCreateTime, cCompany.getCreateTime());
        }
        if (cCompany.getUpdateTime() != null) {
            queryWrapper.eq(CCompany::getUpdateTime, cCompany.getUpdateTime());
        }


        List selectList = companyMapper.selectList(queryWrapper);
        PageInfo<Dict> info = new PageInfo<>(selectList);


        System.out.println(info.getList());
        return ResultUtil.successCount(info.getList(), info.getTotal());

    }


}